<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\AdminController;
use Illuminate\Http\Request;
use App\Models\Order as TOrder;
use App\Models\FeeItem;
use App\Models\Good;
use App\Models\Agent;
use App\Models\GoodItem;
use App\Models\GoodOption;
use App\Models\Channel;
use App\Models\FeeGood;

class Order extends AdminController{
    public function index(Request $req){
        $psize = 30;
        if($req->method() == 'POST'){
            $list = TOrder::where('status','!=',0);
            if ($req->input('orderno')) $list->where('ordersn',$req->post('orderno'));
            if ($req->post('transid')) $list->where('transid',$req->post('transid'));
            if ($req->post('nums')) $list->where('nums','like',"%".$req->post('nums')."%");
            $status = $req->post('status',0);
            if ($status == 3) $list->where('status',-1);
            elseif ($status > 0) $list->where('status',$status);
            $gid = $req->post('gid');
            if ($gid) {
                if (strpos('fee', $gid) === false) $list->where('type',str_replace("fee", "", $gid));
                else $list->where('type',10)->where('gid',$gid);
            }
            if ($req->post('op') == 'reset') $list->where('reset',1);
            else $list->where('reset',0);
            $list = $list->orderByDesc('id')->paginate($psize);
            foreach ($list as &$v) {
                $m = Agent::find($v->aid);
                if ($m) {
                    $v->avatar = $m->avatar;
                    $v->nickname = $m->title ? $m->title : '微信用户';
                }else $v->nickname = '用户已删除';
                
                if ($v->type < 10){
                    $v->title = $v->type == 0 ? '话费' : ($v->type == 1 ? '电费' : '燃气费');
                    $v->title .= "<br>".FeeGood::where('id',$v->gid)->value('title')."元";
                }else{
                    $g = Good::find($v->gid);
                    if (!empty($g)) {
                        $v->title = $g->title;
                        $v->logo = getImage($g->logo);
                        $p = json_decode($v->param,1);
                        $v->title .= "-".$p['title'];
                    }else $v->title = '商品已删除';
                }
                if ($v->cid > 0) {
                    $channel = Channel::find($v->cid);
                    $v->channel = $channel->title."<br>".$v->tradeno."<br>￥".$v->costprice;
                }else $v->channel = '-';
                
                if ($v->reback > 0) {
                    $v->rebackinfo = '';
                    if ($v->paid > 0 && $v->preback > 0) {
                        $ag = Agent::find($v->paid);
                        $v->rebackinfo = $ag->title ? $ag->title : $ag->mobile;
                        $v->rebackinfo .= "：<br>￥".$v->preback."<br>";
                    }
                    $ag = Agent::find($v->aid);
                    $v->rebackinfo .= $ag->title ? $ag->title : $ag->mobile;
                    $v->rebackinfo .= "：<br>￥".$v->reback;
                }
                $v->time = '下单：<br>'.date('Y-m-d H:i',$v->createtime);
                if ($v->finishtime > 0) $v->time .= '<br>完成：<br>'.date('Y-m-d H:i',$v->finishtime);
            }
            $data = ['rows' => $list->items(), 'total' => $list->total()];
            wxresp(1, $data);
        }
        return $this->V("index",array('op'=>$req->get('op',''),'orderno'=>$req->input('orderno',''),'goods'=>Good::select('id','title')->get(),'resetnum'=>TOrder::where('status',1)->where('reset',1)->count()));
    }
    
    public function refund(Request $req){
        $oid = $req->post('oid');
        $reason = $req->post('reason');
        $order = TOrder::find($oid);
        if (empty($order)) wxresp(0,'订单不存在');
        if ($order->status == 0) wxresp(0,'订单未支付');
        $res = TOrder::orderFail($order,$reason);
        die(json_encode($res));
    }
    
    public function resubmit(Request $req){
        $oid = $req->post('oid');
        $order = TOrder::find($oid);
        if (empty($order)) wxresp(0,'订单不存在');
        if ($order->type < 10) {
            $item = FeeItem::where('gid',$order->gid)->where('status',0)->orderBy('costprice')->first();
        }else{
            $p = json_decode($order->param,1);
            $item = GoodItem::where('oid',$p['oid'])->where('status',0)->orderBy('costprice')->first();
        }
        if (empty($item)) { //没产品了
            wxresp(0,'没可用渠道');
        }else{
            $channel = Channel::find($item->cid);
            $param = array(
                    'orderno'=>$order->ordersn."_".$order->resetnum,
                    'mobile'=>$order->nums,
                    'itemno'=>$item->itemno,
            );
            $res = Channel::channelPost($channel, 'submit', $param);
            if ($res['code'] != 1) wxresp(0,!isset($res['nocredit']) ? $res['msg'] : '渠道余额不足');
            $order->tradeno = $res['transid'];
            $order->reset = 0;
            $order->resetnum++;
            $order->cid = $item->cid;
            $order->costprice = $item->costprice;
            $order->save();
            wxresp(1);
        }
    }
    
    public function export(Request $req){
        $type = $req->input('type',0);
        $starttime = $req->get('startTime',date('Y-m-d',strtotime('-7 day')));
        $endtime = $req->get('endTime',date('Y-m-d'));
        $list = TOrder::where('dtype',$type)->where('createtime','>=',strtotime($starttime))->where('createtime','>=',strtotime($endtime));
        if ($req->get('did') > 0) $list->where('did',$req->get('did'));
        if ($req->get('nid') > 0) $list->where('nid',$req->get('nid'));
        if ($req->get('orderno')) $list->where('orderno',$req->get('orderno'));
        
        $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();
        $titles = ['订单ID','订单号','网点名称','设备名称','会员','订单金额','退还金额','消费金额','佣金信息','下单时间','归还时间','支付渠道','订单状态','原因'];
        foreach ($titles as $i => $value) {
            $sheet->setCellValue([$i+1,1],$value);
        }
        $list = $list->OrderByDesc('id')->get();
        $nets = $mems = $devices = $sharemen = [];
        foreach ($list as $i => $v) {
            $sheet->setCellValue([1,$i+2],$v->id);
            $sheet->setCellValue([2,$i+2],$v->orderno);
            if (!isset($nets[$v->nid])) $nets[$v->nid] = NetWork::where('id',$v->nid)->value('title');
            $sheet->setCellValue([3,$i+2],$nets[$v->nid]);
            if (!isset($devices[$v->did])) $devices[$v->did] = Device::where('id',$v->did)->value('title');
            $sheet->setCellValue([4,$i+2],$devices[$v->did]);
            if (!isset($mems[$v->mid])) $mems[$v->mid] = Mem::where('id',$v->mid)->value('mobile');
            $sheet->setCellValue([5,$i+2],$mems[$v->mid]);
            $sheet->setCellValue([6,$i+2],$v->price);
            $sheet->setCellValue([7,$i+2],$v->returnprice);
            $sheet->setCellValue([8,$i+2],$v->consume);
            $info = '';
            if ($v->status != 0) {
                $os = OrderShare::where('oid',$v->id)->get()->toArray();
                if ($os) {
                    $rb = [];
                    foreach ($os as $s) {
                        if (!isset($sharemen[$s['sid']])) {
                            if ($s['sid'] == 0) $sharemen[$s['sid']] = '佣金';
                            else $sharemen[$s['sid']] = ShareMen::where('id',$s['sid'])->value('title');
                        }
                        $rb[] = $sharemen[$s['sid']].":￥".$s['price'];
                    }
                    $info = explode("\n", $rb);
                }
            }
            $sheet->setCellValue([9,$i+2],$info);
            $sheet->setCellValue([10,$i+2],date('Y-m-d H:i:s',$v->createtime));
            $sheet->setCellValue([11,$i+2],$v->returntime > 0 ? date('Y-m-d H:i:s',$v->returntime) : '');
            $sheet->setCellValue([12,$i+2],$v->paychannel == 1 ? '聪明付' : '微信');
            $status = '未支付';
            if ($v->status == 1) $status = '进行中';
            elseif ($v->status == 2) $status = '已完成';
            elseif ($v->status == -1){
                $status = '已退款';
                $sheet->setCellValue([14,$i+2],$v->reason);
            }
            $sheet->setCellValue([13,$i+2],$status);
        }
        header("Content-type:application/vnd.ms-excel");
        $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
        $writer->save('php://output');
    }
}